
import { queryNotices, setNoticeReaded, mockNotices } from '@/services/message';

const Message = {
  namespace: 'message',
  state: {
    unReadNoticeCnt: 0,
    unReadMessageCnt: 0,
    unReadEventCnt: 0
  },
  effects: {

    *queryUnReadMessage({ payload }, { call, put }) {
      const response = yield call(queryNotices, {
        isRead: 0
      });
      if (response.success) {
        yield put({
          type: 'setUnReadMessage',
          payload: {
            unReadNotice: response.data.list,
            unReadNoticeCnt: response.data.count
          },
        });
      }
    },

    *queryMockMessage({ payload }, { call, put }) {
      const mockResponse = yield call(mockNotices);
      yield put({
        type: 'setUnReadMessage',
        payload: {
          unReadMessage: mockResponse
        },
      });
    },

    *setNoticeReaded({ payload }, { call, put }) {

      const response = yield call(setNoticeReaded, payload);
      if (response && response.success) {
        yield put({
          type: 'setNoticeReadedAndMinCount',
          payload: payload
        });
      }
    },

    *clearUnReadNotice({ payload }, { call, put }) {
      if (!payload || payload.length === 0) {
        return
      }
      const response = yield call(setNoticeReaded, payload.join(","));
      if (response && response.success) {
        yield put({
          type: 'setClearNoticeCnt',
          payload: payload
        });
      }
    }
  },
  reducers: {
    setUnReadMessage(state, action) {
      return { ...state, ...action.payload };
    },
    setClearNoticeCnt(state, action) {
      let unReadNoticeCnt = state.unReadNoticeCnt - action.payload.length;
      return {
        ...state,
        isNeedReQuery: unReadNoticeCnt > 0,
        unReadNotice: [],
        unReadNoticeCnt: unReadNoticeCnt
      };
    },
    setNoticeReadedAndMinCount(state, action) {
      if (!state.unReadNotice) {
        return { ...state };
      }
      state.unReadNotice.map(notice => {
        if (notice.id === action.payload) {
          notice.isRead = 1;
        }
        return notice;
      });
      return {
        ...state,
        unReadNoticeCnt: state.unReadNoticeCnt - 1
      };
    }
  },
};
export default Message;
